package com.woniuxy.service.impl;


import com.aliyun.oss.OSS;
import com.aliyun.oss.model.ObjectMetadata;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.woniuxy.ResponseResult;
import com.woniuxy.ServerResponse;
import com.woniuxy.entity.Shopinfo;
import com.woniuxy.exception.EmailExistException;
import com.woniuxy.mapper.ShopinfoMapper;
import com.woniuxy.service.ShopinfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.utils.MailUtil;
import lombok.experimental.SuperBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 
 * @since 2021-03-23
 */
@Service
@SuppressWarnings("all")
@Slf4j
public class ShopinfoServiceImpl extends ServiceImpl<ShopinfoMapper, Shopinfo> implements ShopinfoService {
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private  ShopinfoMapper shopinfoMapper;
    @Autowired
    private OSS ossClient;

    @Override
    public ServerResponse<Void> register(Shopinfo shopinfo) {
        //判断邮箱是否存在
        QueryWrapper<Shopinfo> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("account",shopinfo.getAccount());
        Integer value = shopinfoMapper.selectCount(queryWrapper);
        log.debug("value="+value);
        //邮箱重复则抛出异常
        if(value>0){
         throw new EmailExistException("该邮箱已经注册");
        }
        shopinfoMapper.insert(shopinfo);


        //插入注册数据
        return ServerResponse.createBySuccessMessage("注册成功");
    }

    @Override
    public ResponseResult<Void> updateAvator(MultipartFile file)  throws  Exception{

        //查看是否已经存在头像
          QueryWrapper<Shopinfo> swrapper = new  QueryWrapper<Shopinfo>();
        int id = 1;
        swrapper.eq("id",id);
        Shopinfo shopinfo = shopinfoMapper.selectOne(swrapper);
// 如果存在图片删除原来的图片
        if(shopinfo.getAvator()!=null&&!"".equals(shopinfo.getAvator())){
          String imgavator = shopinfo.getAvator();
            log.debug("buketwei="+imgavator.substring(imgavator.indexOf("//")+2,imgavator.indexOf(".")));
            log.debug("key = "+imgavator.substring(imgavator
                    .lastIndexOf("com")+3));
            ossClient.deleteObject(imgavator.substring(imgavator.indexOf("//")+2,imgavator.indexOf(".")),imgavator.substring(imgavator
            .lastIndexOf("com")+4));

        }
        String avaMd5 = null;
        //设置桶名称
        String bucketName = "shopinfoimg";
        String fileNames = file.getOriginalFilename();

        String suffix = fileNames.substring(fileNames.lastIndexOf(".")).toLowerCase();
        File files = new File("C:\\Users\\xxhcm\\Desktop\\2"+suffix);
        if(!files.exists()){
            files.createNewFile();
        }
        file.transferTo(files);
        FileInputStream fileInputStream = null;
//        log.info("value="+inputStream.available());

        try {
            fileInputStream = new FileInputStream(files);
            //判断文件是否重复
//            avaMd5 = DigestUtils.md5Hex(inputStream);
            boolean  flag = ossClient.doesBucketExist(bucketName);
            //如果桶不存在则创建桶
            if(!ossClient.doesBucketExist(bucketName)){
                log.info("this is ");
                ossClient.createBucket(bucketName);
            }
            //设置图片名
            String fileName = UUID.randomUUID().toString();


            ossClient.putObject(bucketName,"avator/"+fileName+suffix,fileInputStream);


            //得到图片具体url
        URL url = ossClient.generatePresignedUrl(bucketName, "avator/"+fileName+".png", new Date());
        String avatorUrl  = url.toString().split("[?]")[0];
        UpdateWrapper<Shopinfo> wrapper = new UpdateWrapper<>();
            //构造查询条件
        wrapper.eq("id",1);
        //将数据插入数据库
        shopinfoMapper.update(new Shopinfo().setAvator(avatorUrl),wrapper);
            return ResponseResult.SUCCESS;
        } catch (IOException e) {

            throw new IOException("io异常");

        }finally {

            fileInputStream.close();
            files.delete();
        }


    }

    @Override
    public ServerResponse<Void> send(String account) {
        Random random = new Random();
//        生成验证码
        String code = "";
        for (int i = 0; i <6 ; i++) {
            code += random.nextInt(10);

        }
//        存储在redis中并且设置过期时间
        redisTemplate.opsForValue().set(account,code,5, TimeUnit.MINUTES);
//        MailUtil.sendCode(account,javaMailSender,"登录验证码为:"+code);
            Map<String,String> map = new HashMap<>();

        map.put(account,"你的登录验证码为:"+code);
        rabbitTemplate.convertAndSend("mailExchange","codeKey",map);

        return ServerResponse.createBySuccess();
    }

    @Override
    public ServerResponse<Void> codeLogin(String account, String code) {
        QueryWrapper<Shopinfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account",account);
        Shopinfo shopinfo = shopinfoMapper.selectOne(queryWrapper);
//        查询账号若没有则未注册
        if(shopinfo==null){
            return ServerResponse.createByErrorCodeMessage(404,"账号未注册");
        }
        String generateCode = (String)redisTemplate.opsForValue().get(account);
//        验证用户输入的验证码 如果不相等 则返回错误信息
        if(!generateCode.equals(code)){
            return ServerResponse.createByErrorMessage("验证码错误");
        }
      return ServerResponse.createBySuccess();
    }

    @Override
    public ResponseResult< Map<String,Object>> getShopInfoDetailById(Integer id) {

        QueryWrapper<Shopinfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",id);
       int count = shopinfoMapper.selectCount(queryWrapper);
        ResponseResult result = new ResponseResult();
        if(count==0){
         result.setCode(100);
            result.setMsg("无此商店");
            return result;
        }
        result.setCode(200);
        List<Map<String, Object>> maps = shopinfoMapper.selectMaps(queryWrapper);
        result.setData(maps.get(0));
        return result;

//        return null;
    }
}
